<?php


namespace app\api\controller\v1\untils;



use app\admin\model\SystemUploadfile;
use app\admin\service\UploadService;
use app\api\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\file\UploadedFile;
use think\response\Json;

class Upload extends Api
{


    /**
     * 上传文件
     */
    public function upload()
    {
        $this->checkPostRequest();
        $type         = $this->request->param('type', '');
        $data         = [
            'file'        => $this->request->file($type == 'editor' ? 'upload' : 'file'),
        ];
        $uploadConfig = sysconfig('upload');

        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'                    => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        $upload_type = $uploadConfig['upload_type'];
        try {
            $upload = UploadService::instance()->setConfig($uploadConfig)->$upload_type($data['file'], $type);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $code = $upload['code'] ?? 0;
        if ($code == 0) {
            return $this->error($upload['data'] ?? '');
        } else {
            $upload['data']['url'] = $this->request->domain().$upload['data']['url'];
            $this->success('上传成功', $upload['data'] ?? '');
        }
    }






}